/**
 * @author HuntBao
 * @context Role View
 */
 App.Views.RoleView = Backbone.View.extend({
     
 	 template: tpl.roleItem,
 	 
 	 className: 'role-row',
 	 
 	 events: {
 	 	'click': 'clickRowHandler',
        'click .delete-role': 'deleteRoleHandler',
        'click .delete-role-confirm': 'deleteRoleConfirmHandler',
        'click .delete-role-cancel': 'deleteRoleCancelHandler',
        'click .edit-role': 'editRoleHandler',
        'keydown .role-inp': 'keydowHandler',
        'click .add-role-confirm': 'updateRoleHandler',
        'click .add-role-cancel': 'cancelAddRoleHandler',
        'click .cb': 'updateUIPrivilegesHandler',
        'click .toggle-icon': 'toggleHandler',
        'dblclick': 'toggleHandler'
 	 },
 	 
 	 titles: {
        deleteRoleTitle: App.i18n.get('deleteRole'),
        addRoleTitle: App.i18n.get('addRole'),
        updateRole: App.i18n.get('updateRole'),
        editRoleTitle: App.i18n.get('editRole'),
        editRoleInpPH: App.i18n.get('createRolePlaceholder'),
        addRoleConfirmTitle: App.i18n.get('ok'),
        addRoleCancelTitle: App.i18n.get('cancel'),
        deleteRoleConfrimTitle: App.i18n.get('confirmDelete'),
        deleteRoleCancelTitle: App.i18n.get('cancel'),
        loadingTip: App.i18n.get('loadingTip'),
        canReadPH: App.i18n.get('read'),
        canWritePH: App.i18n.get('write'),
        canDeletePH: App.i18n.get('delete'),
        canXPH: App.i18n.get('xPrivilege')
 	 },
 	 
     initialize : function() {
 		 var self = this;
         self.model.on('change:roleName', self.updateOrCreateRole, self);
         self.model.on('change:memberCount', self.updateMemberCount, self);
         self.model.on('change:expandToggleIcon', self.expandToggleIcon, self);
         self.model.on('change:privileges', self.privilegesChangeHandler, self);
         self.model.on('forceUpdatePrivilege', self.forceUpdatePrivilegeHandler, self);
     },
     
     render: function(){
        var self = this;
        if(self.model.get('memberCount') > 0){
            self.model.set({hasMember: true}, {silent: true});
        }
        var data = self.model.toJSON();
        _.extend(data, self.titles);
        self.$el.html(Mustache.to_html(self.template, data));
        if(self.model.get('default') === true){
            self.$el.addClass('default-role');
        }
        self.viewWrap = self.$el.find('.row-wrap');
        self.roleInp = self.$el.find('.role-inp');
        self.roleName = self.$el.find('.role-name');
        self.toggleIcon = self.$el.find('.toggle-icon');
        self.memberCount = self.$el.find('.member-count');
        self.memberCountNum = self.$el.find('.num');
        self.canRead = self.$el.find('.canread');
        self.canWrite = self.$el.find('.canwrite');
        self.canDelete = self.$el.find('.candelete');
        self.canX = self.$el.find('.canx');
        self.model.get('id') && self.$el.attr('id', App.util.getIdWithPrefix(self.model.get('id')));
		return self;
	 },
	 
	 clickRowHandler: function(e){
        var self = this;
        if(self.model.get('privilegeModal')) return;
        var leftMenuContextMenuView = App.viewInstances.appView.leftMenuContextMenuView;
        leftMenuContextMenuView.removeSelectedItem(e.target);
        leftMenuContextMenuView.updateAddOrganizationModal();
        self.$el.addClass('highlight');
        return false;
	 },
	 
	 deleteRoleHandler: function(e){
        var self = this;
        self.clickRowHandler(e);
        self.$el.addClass('deleting-row');
        return false;
	 },
	 
	 deleteRoleConfirmHandler: function(){
        var self = this,
        model = self.model;
        model.destroy({
            url: App.util.contextPath + '/role/' + model.get('id'),
            success: function(){
                self.$el.remove();
                var defaultRoleId = App.viewInstances.appView.leftMenuContextMenuView.getDefaultRoleId(),
                defaultRoleModel = App.viewInstances.appView.RoleCollection.get(defaultRoleId),
                defaultRoleMemberCount = defaultRoleModel.get('memberCount');
                defaultRoleModel.set('memberCount', defaultRoleMemberCount + self.model.get('memberCount'));
            }
        });
        return false;
	 },
	 
	 deleteRoleCancelHandler: function(){
        var self = this;
        self.$el.removeClass('deleting-row');
        return false;
     },
	 
	 editRoleHandler: function(){
        var self = this;
        self.viewWrap.addClass('editing-row');
        self.roleInp.select();
	 },
	 
	 keydowHandler: function(e){
        var self = this;
        if(e.which === 13){
            self.updateRoleHandler();
        }
	 },
	 
	 updateRoleHandler: function(){
        var self = this;
        var roleName = $.trim(self.roleInp.val());
        self.roleInp.val(roleName);
        if(roleName === ''){
            self.showErrorMsg('createRolePlaceholder');
            self.roleInp.focus();
            return false;
        }
        var roleExist = false;
        App.viewInstances.appView.RoleCollection.every(function(model){
            if(model.get('roleName') === roleName){
                self.showErrorMsg('inputRoleExist');
                self.roleInp.select();
                roleExist = true;
                return false;
            }
            return true;
        });
        if(roleExist) return false;
        self.showErrorMsg();
        self.roleName.text(roleName);
        self.viewWrap.removeClass('editing-row');
        self.model.set('roleName', roleName);
        return false;
	 },
	 
	 updateOrCreateRole: function(){
        var self = this;
        if(self.model.get('id')){
            //update role
        	self.model.save(null, {
                url: App.util.contextPath + '/role'
            });
        }else{
        	//create role
            self.model.save(null, {
                url: App.util.contextPath + '/role',
                success: function(model){
                	 model.set('editingRow', false);
                	 self.render();
                     App.viewInstances.appView.RoleCollection.add(model);
                }
            });
        }
	 },
	 
	 cancelAddRoleHandler: function(){
        var self = this;
        if(!self.model.get('id')){
            self.$el.remove();
        }else{
            self.viewWrap.removeClass('editing-row');
            self.roleInp.val(self.model.get('roleName'));
        }
        self.showErrorMsg();
        return false;
	 },
	 
	 toggleHandler: function(e){
        var self = this;
        if(self.model.get('privilegeModal')) return;
        if(self.model.get('memberCount') === 0) return;
        App.viewInstances.appView.leftMenuContextMenuView.expandOrCollapseRole(self.$el, !self.model.get('expandToggleIcon'));
        return false;
	 },
	 
	 updateMemberCount: function(){
        var self = this;
        self.memberCountNum.text(self.model.get('memberCount'));
        if(self.model.get('memberCount') === 0){
            self.toggleIcon.removeClass('visible');
            self.memberCount.removeClass('visible');
            self.model.set({'expandToggleIcon': false}, {silent: true});
        }else{
            self.toggleIcon.addClass('visible toggle-icon-expand');
            self.memberCount.addClass('visible');
            self.model.set({'expandToggleIcon': true}, {silent: true});
        }
	 },
	 
	 expandToggleIcon: function(){
        var self = this;
        if(self.model.get('expandToggleIcon')){
            self.toggleIcon.addClass('toggle-icon-expand');
        }else{
            self.toggleIcon.removeClass('toggle-icon-expand');
        }
	 },
	 
	 getCurrentUIPrivileges: function(){
        var self = this,
        cbs = self.$el.find('.cb'),
        uiPrivileges = {};
        _.each(cbs, function(cb){
            cb = $(cb);
            if(cb.is(self.canRead)){
                uiPrivileges.readChecked = cb[0].checked;
                uiPrivileges.readDisabled = cb[0].disabled;
            }else if(cb.is(self.canWrite)){
                uiPrivileges.writeChecked = cb[0].checked;
                uiPrivileges.writeDisabled = cb[0].disabled;
            }else if(cb.is(self.canDelete)){
                uiPrivileges.deleteChecked = cb[0].checked;
                uiPrivileges.deleteDisabled = cb[0].disabled;
            }else if(cb.is(self.canX)){
                uiPrivileges.xChecked = cb[0].checked;
                uiPrivileges.xDisabled = cb[0].disabled;
            }
            if(uiPrivileges.writeChecked || uiPrivileges.deleteChecked){
                if(!self.canRead.is('.inherit')){
                    uiPrivileges.readChecked = true;
                    uiPrivileges.readDisabled = true;
                }
            }else{
                if(!self.canRead.is('.inherit')){
                    uiPrivileges.readDisabled = false;
                }
                uiPrivileges.xDisabled = false;
            }
            if(uiPrivileges.readChecked || uiPrivileges.writeChecked || uiPrivileges.deleteChecked){
                uiPrivileges.xChecked = true;
                uiPrivileges.xDisabled = true;
            }
        });
        return uiPrivileges;
	 },
	 
	 getPrivilegesArr: function(uiPrivileges){
        var self = this;
        var privilegesMap = {
            writeChecked: 'w',
            deleteChecked: 'd',
            readChecked: 'r',
            xChecked: 'x'
        }
        var privilegesArr = [];
        for(var p in privilegesMap){
            if(uiPrivileges[p]){
                privilegesArr.push(privilegesMap[p]);
            }
        }
        return privilegesArr;
	 },
	 
	 updateUIPrivilegesHandler: function(e){
        var self = this;
        clearTimeout(self.updatePrivilegeTimer);
        var uiPrivileges = self.getCurrentUIPrivileges(),
        privilegesArr = self.getPrivilegesArr(uiPrivileges);
        self.model.set(uiPrivileges);
        self.render();
        self.updatePrivilegeTimeout = 3000;
        self.updatePrivilegeTimer = setTimeout(function(){
            self.model.set('privileges', privilegesArr.join(','));
        }, self.updatePrivilegeTimeout);
	 },
	 
	 privilegesChangeHandler: function(){
        var self = this;
        self.updatePrivileges();
	 },
	 
	 updatePrivileges: function(){
	 	var self = this;
	    var privilegeModel = new App.Models.itemModel({
            fileId: self.model.get('fileId'),
            privileges: self.model.get('privileges').split(','),
            role: {
                id: self.model.get('id')
            }
        });
        //update privilege
        privilegeModel.save(null, {
            url: App.util.contextPath + '/privilege',
            success: function(model){
                 
            }
        });
	 },
	 
	 forceUpdatePrivilegeHandler: function(){
        var self = this;
        var uiPrivileges = self.getCurrentUIPrivileges(),
        privilegesArr = self.getPrivilegesArr(uiPrivileges);
        self.model.set(uiPrivileges);
        self.updatePrivilegeTimeout = 0;
        self.updatePrivilegeTimer = setTimeout(function(){
            self.model.set('privileges', privilegesArr.join(','));
        }, self.updatePrivilegeTimeout);
	 },
     
     showErrorMsg: function(msg){
        App.viewInstances.appView.leftMenuContextMenuView.roleModalErrorMsg.text(msg && App.i18n.get(msg) || '');
     }
 });
